import 'dart:convert';
import 'dart:io';

import 'package:flutter/services.dart';
import 'package:customer_log_app/global/console.dart';

import 'package:customer_log_app/global/sqlite_helper.dart';

class MyHttpServer {
  void startServer(int port) async {
    try {
      if (Platform.isAndroid || Platform.isFuchsia || Platform.isIOS) {
        log("http server started");

        // int port = getPort();

        for (var interface in await NetworkInterface.list()) {
          for (var addr in interface.addresses) {
            log('${addr.address}:$port');
          }
        }

        HttpServer.bind(InternetAddress.anyIPv4, port, shared: true)
            .then((server) {
          server.listen((HttpRequest request) {
            String route = request.uri.path;
            router(route, request);
          });
        });
      }
    } catch (e) {
      log(e);
    }
  }

  void router(String route, HttpRequest request) async {
    HttpResponse res = request.response;
    // log('reuqest data:' + request.headers.toString());

    var params = request.uri.queryParametersAll;
    log("params:$params");

    switch (route) {
      case '/':
        res.statusCode = 200;
        res.headers.add("Content-Type", "application/json; charset=UTF-8");

        var m = {};

        m["name"] = "test";
        m["name2"] = "test2";

        var list = [];

        SqliteHelper sqlHelper = SqliteHelper();
        String sql = "select * from translation ";
        var transData = await sqlHelper.getData(sql);

        list.add(m);

        var data = <String, dynamic>{};

        data['status'] = 200;
        data['data'] = transData;
        data['success'] = true;
        var json = jsonEncode(data).toString();
        //var json = data.toString();
        res.write(json);
        res.close();

        break;
      case '/data':
        res.statusCode = 200;
        res.headers.add("Content-Type", "application/json; charset=UTF-8");

        var m = {};

        m["name"] = "test";
        m["name2"] = "test2";

        var list = [];
        list.add(m);

        var data = <String, dynamic>{};

        data['status'] = 200;
        data['data'] = list;
        data['success'] = true;
        var json = jsonEncode(data).toString();
        //var json = data.toString();
        res.write(json);
        res.close();

        break;
      case '/index.html':
        res.statusCode = 200;
        res.headers.add("Content-Type", "text/html; charset=UTF-8");
        final response = await rootBundle.loadString('assets/html/index.html');
        res.write(response);
        res.close();
        break;
      case '/element.html':
        res.statusCode = 200;
        res.headers.add("Content-Type", "text/html; charset=UTF-8");
        final response =
            await rootBundle.loadString('assets/html/element.html');
        res.write(response);
        res.close();
        break;
      default:
        res.statusCode = 200;
        // res.headers.add("Content-Type", "text/html; charset=UTF-8");
        // Directory appDocDir = await getApplicationDocumentsDirectory();
        var ext = route.split('.');
        var fileExtension = ext[ext.length - 1];
        var assetsName = 'assets/html$route';
        log('assets_name:$assetsName');
        var response = '';
        switch (fileExtension) {
          case 'css':
            res.headers.add("Content-Type", "text/css; charset=UTF-8");
            try {
              response = await rootBundle.loadString(assetsName);
            } on Exception catch (_) {}
            res.write(response);
            res.close();
            break;
          case 'js':
            res.headers.add("Content-Type", "text/javascrip; charset=UTF-8");
            try {
              response = await rootBundle.loadString(assetsName);
            } on Exception catch (_) {}
            res.write(response);
            res.close();
            break;
          case 'png':
          case 'jpg':
            log('load png:$assetsName');
            res.headers.add("Content-Type", "image/png");
            // var fileResponse;
            try {
              // fileResponse = (await rootBundle.load(assetsName));
              File f = File(assetsName);
              var raw = f.readAsBytesSync();
              res.headers.set('Content-Type', 'image/png');
              res.headers.set('Content-Length', raw.length);
              res.add(raw);
            } on Exception catch (_) {
              // log('load error>:' + e.toString());
            }
            res.close();
            break;
        }

        // String appDocPath = appDocDir.path;
        // res.write('current route' + route + " app path:" + appDocPath);

        break;
    }
  }
}
